package com.lyandwc.lw_bbs.controller;

import com.alibaba.fastjson.JSONObject;
import com.lyandwc.lw_bbs.service.TagService;
import com.lyandwc.lw_bbs.utils.ResponseUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/tags")
public class TagController {
    private TagService tagService;

    public TagController(TagService tagService) {
        this.tagService = tagService;
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN', 'USER')")
    @RequestMapping(method = RequestMethod.GET)
    public JSONObject listTags() {
        return ResponseUtils.success(tagService.list());
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN')")
    @RequestMapping(method = RequestMethod.POST)
    public JSONObject addTag(
            @RequestBody Map<String, String> map
    ) {
        String name = map.get("name");
        if (name != null) {
            return ResponseUtils.success(tagService.findOrInsertTag(name));
        }
        return ResponseUtils.fail("Illegal format params.");
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN')")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public JSONObject deleteTag(
            @PathVariable int id
    ) {
        tagService.removeById(id);
        return ResponseUtils.success(null);
    }
}
